﻿using Data;
using Factory;
using Services.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Hero
{
    public class HeroShoot : MonoBehaviour
    {
        public event Action Shot;

        public float Delay { get; set; }

        [SerializeField] private List<Transform> _shootPoints;
        private PlayerControls _controls;
        private IInputService _inputService;
        private IGameFactory _gameFactory;
        private HeroState _state;
        private float _shoot;
        private float _shootTime = float.MinValue;

        public void Construct(IInputService inputService, IGameFactory gameFactory, HeroState state)
        {
            _inputService = inputService;
            _gameFactory = gameFactory;
            _state = state;
            _controls = _inputService.GetControls();
            _controls.Enable();
            InitGuns();
        }

        private void Update()
        {
            _shoot = _controls.Player.Shoot.ReadValue<float>();

            if (_shoot > 0)
                Shoot();
        }

        public void InitGuns()
        {
            foreach (var point in _shootPoints) 
                point.gameObject.SetActive(false);
            for (var i = 0; i < _state.CurrentGuns; i++)
                _shootPoints[i].gameObject.SetActive(true);
        }

        private void Shoot()
        {
            if (Time.time < _shootTime + Delay) return;
            if (_state.CurrentAmmo <= 0) return;

            foreach (var point in _shootPoints.Where(point => point.gameObject.activeSelf))
                _gameFactory.CreateBullet(point.position, transform.rotation);

            _shoot = 0;
            _shootTime = Time.time;
            ConsumeAmmo();
        }

        private void ConsumeAmmo()
        {
            _state.CurrentAmmo--;
            Shot?.Invoke();
        }
    }
}